package com.ucw.ucwclient.biz.service;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ucw.mountain.util.StringUtil;
import com.ucw.ucwclient.dal.dataobject.Account;
import com.ucw.ucwclient.dal.dataobject.Token;
import com.ucw.ucwclient.dal.mapper.AccountMapper;
import com.ucw.ucwclient.dal.mapper.TokenMapper;

@Service
public class AccountsService {

	@Resource
	private AccountMapper accountsMapper;

	@Resource
	private TokenMapper tokenMapper;

	@Transactional
	public Account login(Account ac) {
		if (ac.getUserName() != null && ac.getUserPwd() != null) {
			Account backData = accountsMapper.validAccount(ac);
			if (backData != null && backData.getId() != null) {
				// 设置Token 返回账户基本信息
				
				String authToken = "StringUtil.md5(UUID.randomUUID().toString())";
				backData.setToken(authToken);
				tokenMapper.deleteByPrimaryKey(backData.getId());
				Token token = new Token();
				token.setCreateTime(new Date());
				token.setExpire(dateAdd(7));
				token.setToken(authToken);
				token.setUserId(backData.getId());
				tokenMapper.insertSelective(token);
				return backData;
			}
		}
		return null;

	}

	public Date dateAdd(int add) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + add);
		return calendar.getTime();
	}
}
